<?php

namespace App\Services\Api;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class BulletSwooleService extends ApiService
{

    /**
     * 建立连接
     * @method onOpen
     * @author chengzhigang<1256699215@qq.com>
     */
    public function onOpen($serv, $request)
    {
        Log::info('onOpen');
        $param = $request->get;
        $room_id = $param['room_id'];
        $result = $this->getRoomSpeck($serv,$room_id);
        $this->addRoom($room_id,$request->fd);//加入房间
        return ['status'=>1,'msg'=>'请求成功','data'=>['active'=>'connect','data'=>$result]];
    }

    public function onMessage($serv, $frame)
    {
        $data = json_decode($frame->data,true);
        $room_id = $data['room_id'];
        $result = [];
        if($data['active']=='speck'){
            $result = $this->addSpeck($room_id,$frame->fd,$data);
        }
        return ['status'=>1,'msg'=>'请求成功','data'=>['active'=>$data['active'],'data'=>$result]];
    }

    //加入房间
    public function addRoom($room_id,$fd){
        $roomInfo = [
            'room_id' => $room_id,
            'fd' => $fd,
            'nick_name' => createNickname()
        ];
        Redis::hSet('Room:'.$room_id,$fd,json_encode($roomInfo));
    }

    //删除弹幕
    public function clearRoomSpeck($serv,$room_id){
        $fds = Redis::hKeys('Room:'.$room_id);
        foreach ($fds as $fd) {
            Redis::del('Speck:' . $room_id.':'.$fd);
        }
    }

    //获取历史弹幕
    public function getRoomSpeck($serv,$room_id){
        $historySpeck = [];
        $fds = Redis::hKeys('Room:'.$room_id);
        foreach ($fds as $fd) {
            $speckData = Redis::lRange('Speck:' . $room_id.':'.$fd,0,-1);
            foreach($speckData as $v){
                $historySpeck[] = $v;
            }
        }
        return $historySpeck;
    }

    //存储弹幕
    public function addSpeck($room_id,$fd,$data){
        $speckInfo = [
            'room_id' => $room_id,
            'fd' => $fd,
            'msg' => $data['msg'],
            'time' => $data['time'],
            'speed' => $data['speed'],
            'color' => $data['color']
        ];
        Redis::rPush('Speck:'.$room_id.':'.$fd,json_encode($speckInfo));
        return $speckInfo;
    }

    public function onClose($serv, $fd)
    {
        Log::info('onClose');
        echo "标识{$fd}关闭了连接\n";
    }

    public function onRequest($request, $response)
    {
        Log::info('onRequest');
    }
}
